package zsc.gof.dao.luence;

import java.io.File;


import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import zsc.gof.dao.PremisesDao;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/config/application*.xml"})
public class IndexQuery {
	@Autowired
	PremisesDao dao;
	@Test public void search(){
		QueryParser parser = new QueryParser("address",new StandardAnalyzer());
		try {
			//
			
			Directory directory = FSDirectory.open(new File("A:\\index"));
			IndexReader reader = DirectoryReader.open(directory);
			IndexSearcher searcher = new IndexSearcher(reader);
			
			//通过search来搜索索引库
			Query query = parser.parse("address:区");
			TopDocs docs = searcher.search(query, 10);
			
			//根据查询条件匹配出的记录总数
			int count = docs.totalHits;
			ScoreDoc scoreDocs[] = docs.scoreDocs;
			for(ScoreDoc s:scoreDocs){
				int docId = s.doc;
				Document documentTmp = searcher.doc(docId);
				System.out.printf("%s : %s\n",documentTmp.get("build"),documentTmp.get("address"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
